/**
 * 
 * Copyright 2013 by Hai Nguyen 
 *
 */

package com.avj.g17.chat.server.util;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

/**
 * XMLFunctions
 *
 * @author Hai Nguyen <hain186@gmail.com>
 * @version $Id: XMLFunctions Mar 26, 2013 11:00:13 PM hainn $   
 */
public class XMLFunctions {

    public XMLFunctions() {
    }
    
    public Document loadXMLFile(String fileName) throws ParserConfigurationException, SAXException, IOException {
            
            File f = new File(fileName);
            DocumentBuilderFactory dpf = DocumentBuilderFactory.newInstance();
            DocumentBuilder bd = dpf.newDocumentBuilder();
            Document doc = bd.parse(f);
            return doc;
    }
    
    public NodeList getNodesByXpath(String xquery, Document docLoad){
        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList list = (NodeList) xpath.evaluate(xquery, docLoad, XPathConstants.NODESET);
            if (list.getLength() > 0) {
                return list;
            }
        } catch (XPathExpressionException ex) {
            Logger.getLogger(XMLFunctions.class.getName()).log(Level.SEVERE, null, ex.getMessage());
        }
         return null;
    }

    public Element createElementText(Document docLoad, String elementName, String elementValue){
        Element name = docLoad.createElement(elementName);
        Text tValue = docLoad.createTextNode(elementValue);
        name.appendChild(tValue);
        return name;
    }

    public void writePrettyXML(org.w3c.dom.Document node, String fileName) throws java.io.IOException   {
         org.jdom.input.DOMBuilder builder = new org.jdom.input.DOMBuilder();
         org.jdom.Document doc1 = builder.build(node);
         org.jdom.output.Format format = org.jdom.output.Format.getPrettyFormat();
         org.jdom.output.XMLOutputter output = new org.jdom.output.XMLOutputter(format);
         output.output(doc1, new java.io.FileWriter(fileName));
    }

}

